package com.fw.system.web.service.impl;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fw.common.IdXD;
import com.fw.constant.Constant;
import com.fw.core.redis.RedisCache;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.system.web.dao.FwShangjiaMapper;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.vo.OutputVo;
import com.fw.system.web.model.vo.StorageVo;
import com.fw.system.web.service.*;
import com.fw.utils.RandomUtils;
import com.fw.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 商甲发行表 服务实现类
 * </p>
 *
 * @author
 * @since 2021-05-10
 */
@Service
@Slf4j
public class FwShangjiaServiceImpl extends ServiceImpl<FwShangjiaMapper, FwShangjia> implements IFwShangjiaService {
    @Autowired
    private FwShangjiaMapper shangjiaMapper;
    @Autowired
    private IFwTurnoverService turnoverService;
    @Autowired
    private IFwDisappearGetService disappearGetService;
    @Autowired
    private IFwRuleDatasService ruleDatasService;
    @Autowired
    private IFwUljoinService uljoinService;
    @Autowired
    private IFwMoneysService moneysService;
    @Autowired
    private IFwLockStorageService lockStorageService;
    @Autowired
    private IdXD idXD;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IFwLogsService logsService;
    @Autowired
    private IFwIdentityService identityService;
    @Autowired
    private IFwUserService userService;

    @Autowired
    private IFwDisappearFreedService disappearFreedService;
    @Autowired
    private IFwCurrencyLogService fwCurrencyLogService;


    /**
     * 商甲增长
     */
    @Override
    public void addTurnover(String userId) {
        //获取所有消证获取记录  忽略商户这边的消证统计
        /*List<FwDisappearGet> list = disappearGetService.list(Wrappers.<FwDisappearGet>lambdaQuery().ne(FwDisappearGet::getDisappearSource,Constant.ShopRuleData.SHOP_COUNT_DIS));
        //判空
        if (list.isEmpty()) {
            return;
        }*/
        //初始化标记disappearCount,用来保存消证总量
        BigDecimal disappearCount = new BigDecimal("0");
        //遍历所有消证获取记录,获取消证总量
        double sumDisappear = logsService.getDisappearTotal(null).stream().mapToDouble(o -> Double.parseDouble(o.getFormInfo())).sum();
        //disappearCount=new BigDecimal(list.stream().mapToDouble(o->o.getDisappear().doubleValue()).sum());
        disappearCount = new BigDecimal(sumDisappear);
        /*for (FwDisappearGet fwDisappearGet : list) {

            BigDecimal bigDecimal = fwDisappearGet.getDisappear();
            disappearCount = disappearCount.add(bigDecimal);
        }*/
        //获取上次消证增长
        FwCurrencyLog fwCurrencyLog = fwCurrencyLogService.getOne(Wrappers.<FwCurrencyLog>lambdaQuery().eq(FwCurrencyLog::getLogType, "6").orderByDesc(FwCurrencyLog::getCreateTime).last("limit 1"));
        BigDecimal lastDisapperCount = new BigDecimal(0);
        if (!ObjectUtil.isEmpty(fwCurrencyLog)) {
            lastDisapperCount = fwCurrencyLog.getLogCount();
        }
        //获取当前商甲价格
        FwShangjia fwShangjia = shangjiaMapper.selectOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID));
        BigDecimal presentPrice = fwShangjia.getPresentPrice();
        //获取商甲增长规则数据，商甲价格小于现价，最终商家价格大于现价
        FwTurnover serviceOne = turnoverService.getOne(Wrappers.<FwTurnover>lambdaQuery()
                .le(FwTurnover::getMoney, presentPrice)
                .gt(FwTurnover::getEndMoney, presentPrice));
        //超过了价格阶梯
        if (null == serviceOne) {
            FwTurnover endMoneyLast = turnoverService.getOne(Wrappers.<FwTurnover>lambdaQuery().orderByDesc(FwTurnover::getEndMoney).last("limit 1"));
            if (endMoneyLast != null && presentPrice.compareTo(endMoneyLast.getEndMoney()) > -1) {
                BigDecimal subtract = disappearCount.subtract(lastDisapperCount);
                BigDecimal divideCount = subtract.divide(endMoneyLast.getConsumptionQuota(), 0, BigDecimal.ROUND_DOWN);
                if (divideCount.compareTo(new BigDecimal(1)) > -1) {
                    presentPrice = divideCount.multiply(endMoneyLast.getGrowth()).add(presentPrice);
                    fwShangjia.setPresentPrice(presentPrice);
                    fwCurrencyLog.setLogCount(lastDisapperCount.add(divideCount.multiply(endMoneyLast.getConsumptionQuota())));
                }
            }
        } else {
            //获取详细数据
            BigDecimal growth = serviceOne.getGrowth();//获取增长幅度
            BigDecimal consumptionQuota = serviceOne.getConsumptionQuota();//获取消费额度
            //标记乘以消证总量
            //BigDecimal multiply = count.multiply(disappearCount);
            //获取到下一阶段的价格增长规则
            FwTurnover serviceTwo = turnoverService.getOne(Wrappers.<FwTurnover>lambdaQuery()
                    .eq(FwTurnover::getMoney, serviceOne.getEndMoney()));
            //消证总量减去↑
            BigDecimal subtract = disappearCount.subtract(lastDisapperCount);
            BigDecimal divideCount = subtract.divide(consumptionQuota, 0, BigDecimal.ROUND_DOWN);
            if (divideCount.compareTo(new BigDecimal(1)) > -1) {//判断是否满足商甲价格提升条件
                BigDecimal presentPricePre = divideCount.multiply(growth).add(presentPrice);
                if (ObjectUtil.isEmpty(serviceTwo)) {
                    //已经到了最后一个阶段
                    presentPrice = divideCount.multiply(growth).add(presentPrice);
                    fwCurrencyLog.setLogCount(lastDisapperCount.add(divideCount.multiply(consumptionQuota)));
                } else {
                    if (presentPricePre.compareTo(serviceTwo.getMoney()) > -1) {//判断是否到达下一阶梯
                        //修改阶梯状态
                        serviceOne.setCount(0);
                        turnoverService.updateById(serviceOne);
                        serviceTwo.setCount(1);
                        turnoverService.updateById(serviceTwo);
                        //计算达到当前阶段结束需要消证
                        BigDecimal oneDiapper = serviceOne.getEndMoney().subtract(presentPrice).divide(growth).multiply(consumptionQuota);
                        BigDecimal subtractTwo = subtract.subtract(oneDiapper);
                        if (subtractTwo.compareTo(serviceTwo.getConsumptionQuota()) > -1) {//判断是否达到下一阶梯的增长条件
                            BigDecimal divideCountTwo = subtract.divide(serviceTwo.getConsumptionQuota(), 0, BigDecimal.ROUND_DOWN);
                            presentPrice = divideCountTwo.multiply(serviceTwo.getGrowth()).add(serviceTwo.getEndMoney());
                            fwCurrencyLog.setLogCount(lastDisapperCount.add(oneDiapper).add(divideCountTwo.multiply(serviceTwo.getConsumptionQuota())));
                        } else {
                            presentPrice = serviceOne.getEndMoney();
                            fwCurrencyLog.setLogCount(lastDisapperCount.add(oneDiapper));
                        }
                    } else {
                        presentPrice = presentPricePre;
                        fwCurrencyLog.setLogCount(lastDisapperCount.add(divideCount.multiply(consumptionQuota)));
                    }
                }
                fwShangjia.setUpdateTime(LocalDateTime.now());
                fwShangjia.setPresentPrice(presentPrice);
                fwShangjia.setUpdateBy(userId);
                shangjiaMapper.updateById(fwShangjia);
                fwCurrencyLog.setId(idXD.nextId());
                fwCurrencyLog.setCreateTime(LocalDateTime.now());
                fwCurrencyLog.setUserId(userId);
                fwCurrencyLog.setLogName("消费销证提升商甲价格为" + presentPrice.toString());
                fwCurrencyLogService.save(fwCurrencyLog);
            }
            //判断是否达到增长标准
            /*int compareTo = subtract.compareTo(consumptionQuota);
            if (compareTo > -1) {
                //若达到标准,标记+1
                count = count.add(new BigDecimal("1"));
                serviceOne.setCount(count.intValue());
                //写入数据库
                turnoverService.updateById(serviceOne);
                //当前商甲价格增长
                presentPrice = presentPrice.add(growth);
                fwShangjia.setPresentPrice(presentPrice);
                //shangjiaService.updateById(fwShangjia);
                *//**
             * 增长成为vip所需消费金额
             *//*
                //判断商甲价格是否达到vip所需消费金额增长标准
            *//*if ("3".equals(serviceOne.getPhase())) {
                //用户成为vip所需消费金额开始增长
                //获取用户成为vip所需消费金额增长的比例
                FwRuleDatas datas = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.BECOME_VIP_MONEY_ID));
                BigDecimal ruleCount = datas.getRuleCount();
                //获取用户成为vip所需消费金额
                FwRuleDatas dataMoney = ruleDatasService.getOne(Wrappers.<FwRuleDatas>lambdaQuery().eq(FwRuleDatas::getId, Constant.IsRuleData.VIP_MONEY_ID));
                BigDecimal countMoney = dataMoney.getRuleCount();
                //增长
                BigDecimal decimal = countMoney.multiply(ruleCount).multiply(new BigDecimal("0.01"));
                BigDecimal add = decimal.add(countMoney);
                dataMoney.setRuleCount(add);
                //写入数据库
                ruleDatasService.updateById(dataMoney);
            }*//*
            }*/
        }

    }

    /**
     * 商甲产出数据统计
     */
    @Override
    public void output() {
        //创建返回vo对象
        OutputVo outputVo = new OutputVo();
        //获取vip总数量
        List<FwUljoin> vipUljoins = uljoinService.list(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIdentityId, Constant.Identity.VIP_ID));
        int vipCount = vipUljoins.size();
        //填充数据
        outputVo.setVipCount(vipCount);
        //获取当前时间
        LocalDateTime now = LocalDateTime.now();
        //获取最近一年成为vip的人数
        LocalDateTime minusYears = now.minusYears(1);//当前时间减一年,去年这个时间
        List<FwUljoin> vipYearUljoins = uljoinService.list(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIdentityId, Constant.Identity.VIP_ID)
                .gt(FwUljoin::getCreateTime, minusYears)//查询所有创建时间比去年这个时间大的数据
        );
        int vipYearsCount = vipYearUljoins.size();
        //填充数据
        outputVo.setVipYearsCount(vipYearsCount);
        //获取最近一个月成为vip的人数
        LocalDateTime minusMonths = now.minusMonths(1);//当前时间减去一个月,上个月这个时间
        List<FwUljoin> vipMonthUljoins = uljoinService.list(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIdentityId, Constant.Identity.VIP_ID)
                .gt(FwUljoin::getCreateTime, minusMonths)//查询所有创建时间比上个月这个时间大的数据
        );
        int vipMonthCount = vipMonthUljoins.size();
        //填充数据
        outputVo.setVipMonthCount(vipMonthCount);
        //获取最近一天成为vip的人数
        LocalDateTime minusDays = now.minusDays(1);//当前时间减去一天,昨天这个时间
        List<FwUljoin> vipDayUljoins = uljoinService.list(Wrappers.<FwUljoin>lambdaQuery().eq(FwUljoin::getIdentityId, Constant.Identity.VIP_ID)
                .gt(FwUljoin::getCreateTime, minusDays)//查询所有创建时间bi昨天这个时间大的数据
        );
        int vipDayCount = vipDayUljoins.size();
        //填充数据
        outputVo.setVipDayCount(vipDayCount);
        //获取当前商甲价格
        FwShangjia fwShangjia = shangjiaMapper.selectOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID));
        BigDecimal presentPrice = fwShangjia.getPresentPrice();
        //填充数据
        outputVo.setPresentPrice(presentPrice);
        //获取恒定增长条件
        FwTurnover serviceOne = turnoverService.getOne(Wrappers.<FwTurnover>lambdaQuery()
                .ge(FwTurnover::getMoney, presentPrice)
                .ne(FwTurnover::getEndMoney, presentPrice));
        //获取增长数据
        BigDecimal growth = serviceOne.getGrowth();//0.01(元)
        BigDecimal multiply = growth.multiply(new BigDecimal("100"));//乘以一百  1(分)
        //获取消费额度
        BigDecimal consumptionQuota = serviceOne.getConsumptionQuota();
        //填充数据
        outputVo.setGrowthConditions(consumptionQuota + "涨" + multiply + "分");
        //存入redis
        String s = JSONObject.toJSONString(outputVo);
        redisCache.setCacheObject("out_put", s);
    }

    /**
     * 商甲存储数据统计
     */
    @Override
    public void shangJiaStorage() {
        //创建商甲存储vo
        StorageVo storageVo = new StorageVo();
        //获取当前商甲价格
        FwShangjia shangjia = shangjiaMapper.selectOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID));
        BigDecimal presentPrice = shangjia.getPresentPrice();//商甲现价
        storageVo.setPresentPrice(presentPrice);
        //获取现有商甲  此处查询的是钱包内的商甲
        List<FwMoneys> moneys = moneysService.list();//钱包内的商甲余额
        //初始化现有商甲
        BigDecimal moneyJia = new BigDecimal("0");
        for (FwMoneys money : moneys) {
            moneyJia = moneyJia.add(money.getShangJia());
        }
        storageVo.setNowCount(moneyJia);//写入vo
        //获取锁仓商甲
        List<FwLockStorage> lockStorages = lockStorageService.list();
        //初始化锁仓商甲
        BigDecimal lockCount = new BigDecimal("0");
        for (FwLockStorage lockStorage : lockStorages) {
            lockCount = lockCount.add(lockStorage.getLockCount());
        }
        storageVo.setLockCount(lockCount);
        //获取系统分红
        List<FwLogs> logs = logsService.list(Wrappers.<FwLogs>lambdaQuery().eq(FwLogs::getIsType, LogsTypeEnum.INTEGRAL_BONUS.getTypeName()));
        //初始化分红数据
        BigDecimal systemCount = new BigDecimal("0");
        for (FwLogs log : logs) {
            systemCount = systemCount.add(new BigDecimal(log.getFormInfo()));
        }
        storageVo.setSystemCount(systemCount);
        //总资产 todo 待完善

        //持商甲总数 todo 待完善

        String s = JSONObject.toJSONString(storageVo);
        redisCache.setCacheObject("storage", s);
    }


    /**
     * 商甲锁仓
     */
    public void lockStorage(String userId) {
        //获取用户钱包数据
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        //获取用户持有商甲数量
        BigDecimal jia = moneys.getShangJia();
        //判断商甲是否达到持有上限
        BigDecimal val = new BigDecimal("1000");
        int flag = jia.compareTo(val);
        //若已达到上限
        if (flag > -1) {
            BigDecimal lockCount = jia.divide(val);//拿到锁仓的倍数
            lockCount = lockCount.setScale(0, BigDecimal.ROUND_DOWN);//lockCount不为0时,向下取整
            lockCount = lockCount.multiply(val);//拿到锁仓的数量
            //锁仓
            FwLockStorage lockStorage = new FwLockStorage();
            lockStorage.setId(idXD.nextId());//id
            lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
            lockStorage.setUserId(userId);//用户编号
            lockStorage.setLockCount(lockCount);//锁仓数量
            lockStorage.setNote(lockCount.toString());//锁仓总量
            lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
            lockStorage.setReleaseTime(LocalDateTime.now());//兑换时间初始化
            lockStorageService.save(lockStorage);
            //新增日志
            logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_LOCK.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓" + lockCount + "商甲", lockCount.toString());
        }
    }

    /**
     * 商甲兑换
     * 将所有锁仓时间满一年的标记改为兑换
     */
    public void releaseFlag() {
        LocalDateTime years = LocalDateTime.now().minusYears(1);
        lockStorageService.update(Wrappers.<FwLockStorage>lambdaUpdate()
                .lt(FwLockStorage::getLockTime, years)
                .eq(FwLockStorage::getFlag, Constant.LockStorage.LOCK_ING)
                .set(FwLockStorage::getFlag, Constant.LockStorage.RELEASE)
        );
    }

    /**
     * 商甲兑换
     * 将所有标记为兑换,且上次兑换时间满七天的兑换
     */
    public void releaseJia() {
        LocalDateTime years = LocalDateTime.now().minusDays(7);
        //获取所有标记为兑换,且上次兑换时间满七天的数据
        List<FwLockStorage> storageList = lockStorageService.list(Wrappers.<FwLockStorage>lambdaQuery().eq(FwLockStorage::getReleaseTime, years));
        //遍历集合
        for (FwLockStorage lockStorage : storageList) {
            //获取需要兑换的数量
            String note = lockStorage.getNote();
            BigDecimal count = new BigDecimal(0);
            if (StringUtils.isNotEmpty(note)) {
                count = new BigDecimal(note);
            } else {
                count = lockStorage.getLockCount();
            }
            count = count.multiply(new BigDecimal("0.01"));//兑换总量的百分之一
            BigDecimal lockCount = lockStorage.getLockCount();//锁仓数量
            lockCount = lockCount.subtract(count);//减去兑换的
            lockStorage.setLockCount(lockCount);//写入
            lockStorage.setReleaseTime(LocalDateTime.now());//更新兑换时间
            lockStorageService.updateById(lockStorage);
            //获取用户编号
            String userId = lockStorage.getUserId();
            //获取用户钱包数据
            FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
            /** 给用户增加兑换的商甲 */
            BigDecimal jia = moneys.getShangJia();//获取商甲余额
            moneys.setShangJia(jia.add(count));
            moneysService.updateById(moneys);
            /** 新增兑换商甲日志 */
            logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_RELEASE.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓商甲兑换" + count, count.toString());


        }
        //判断是否要锁仓（兑换超过24小时的商甲才能锁仓,若当天兑换的小于等于1000，则直接锁仓）
        List<FwLogs> shangJiaLtOneDay = logsService.getShangJiaLtOneDay(null);
        for (FwLogs log : shangJiaLtOneDay) {
            FwMoneys one = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, log.getBuiId()));
            //判断商甲是否达到持有上限
            BigDecimal val = new BigDecimal("1000");
            int flag = one.getShangJia().compareTo(val);
            //若已达到上限
            if (flag > -1) {
                if (new BigDecimal(log.getFormInfo()).compareTo(val) < 1) {
                    BigDecimal lockCount = new BigDecimal(log.getFormInfo()).divide(val);//拿到锁仓的倍数
                    lockCount = lockCount.setScale(0, BigDecimal.ROUND_DOWN);//lockCount不为0时,向下取整
                    lockCount = lockCount.multiply(val);//拿到锁仓的数量
                    FwLockStorage lockStorage = new FwLockStorage();
                    lockStorage.setId(idXD.nextId());//id
                    lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
                    lockStorage.setUserId(log.getBuiId());//用户编号
                    lockStorage.setLockCount(lockCount);//锁仓数量
                    lockStorage.setNote(lockCount.toString());//锁仓总量
                    lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
                    lockStorage.setReleaseTime(LocalDateTime.now());//兑换时间初始化
                    lockStorageService.save(lockStorage);
                    //新增日志
                    logsService.saveLogs(log.getBuiId(), log.getBuiId(), LogsTypeEnum.MONEY_LOCK.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓" + lockCount + "商甲", lockCount.toString());
                    one.setShangJia(one.getShangJia().subtract(lockCount));
                    moneysService.updateById(one);
                } else {
                    BigDecimal subtractOne = one.getShangJia().subtract(new BigDecimal(log.getFormInfo()));
                    if (subtractOne.compareTo(val) > 0) {
                        BigDecimal lockCount = subtractOne.divide(val);//拿到锁仓的倍数
                        lockCount = lockCount.setScale(0, BigDecimal.ROUND_DOWN);//lockCount不为0时,向下取整
                        lockCount = lockCount.multiply(val);//拿到锁仓的数量
                        FwLockStorage lockStorage = new FwLockStorage();
                        lockStorage.setId(idXD.nextId());//id
                        lockStorage.setLockTime(LocalDateTime.now());//锁仓时间
                        lockStorage.setUserId(log.getBuiId());//用户编号
                        lockStorage.setLockCount(lockCount);//锁仓数量
                        lockStorage.setNote(lockCount.toString());//锁仓总量
                        lockStorage.setFlag(Constant.LockStorage.LOCK_ING);//标记为锁仓
                        lockStorage.setReleaseTime(LocalDateTime.now());//兑换时间初始化
                        lockStorageService.save(lockStorage);
                        //新增日志
                        logsService.saveLogs(log.getBuiId(), log.getBuiId(), LogsTypeEnum.MONEY_LOCK.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "锁仓" + lockCount + "商甲", lockCount.toString());
                        one.setShangJia(one.getShangJia().subtract(lockCount));
                        moneysService.updateById(one);
                    }
                }
            }
        }
    }

    /**
     * 消证兑换,转为积分
     * 每天调用一次
     */
    public void usersReleaseDisappear() {
        List<FwUser> users = userService.list();

        for (FwUser user : users) {
            releaseDisappear(user.getId());
        }
    }

    /**
     * 消证兑换,转为积分
     * 每天调用一次
     */
    public void releaseDisappear(String userId) {
        if (!disappearFreedService.isFlag(userId)) {
            log.info("当前用户编号为:{},已经每天释放过了,不可重复释放.", userId);
            return;
        }
        //获取用户数据
        FwUser user = userService.selectFwUserById(userId);
        if (null == user.getToRelease())
            return;
        //获取用户钱包数据
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, userId));
        //获取用户当前消证总量
        BigDecimal disappear = moneys.getDisappear();
        if (disappear.compareTo(new BigDecimal(0)) > 0) {
            //获取用户当前积分总量
            BigDecimal integral = moneys.getIntegral();
            //获取用户积分兑换比例
            BigDecimal release = user.getToRelease();
            //获取用户兑换的消证 万5 的兑换比例
            BigDecimal disappearCount = RandomUtils.mathNumberTen(release, disappear);
            //从钱包中扣除兑换的消证
            BigDecimal realDisappear = disappear.subtract(disappearCount);
            if (realDisappear.compareTo(NumberUtil.add(0D)) >= 0) {
                moneys.setDisappear(realDisappear);
            } else {
                // 直接扣空
                disappearCount = disappear;
                moneys.setDisappear(NumberUtil.add(0D));
            }

            //增加兑换的积分
            moneys.setIntegral(integral.add(disappearCount));
            moneys.setUpdateTime(LocalDateTime.now());
            moneysService.updateById(moneys);
            //新增消证兑换日志/支出
            logsService.saveLogs(userId, userId, LogsTypeEnum.MONEY_CONSUMPTION.getTypeName(), LogsModelEnum.DISAPPEAR_MODEL.getModelName(), disappearCount + "消证兑换积分", disappearCount.toString());
            disappearFreedService.createFreed(disappearCount, 0, userId, StringUtils.format("{}消证兑换积分", disappear));
            //新增积分增加日志
            logsService.saveLogs(userId, userId, LogsTypeEnum.INTEGRAL_RELEASE.getTypeName(), LogsModelEnum.INTEGRAL_MODEL.getModelName(), disappearCount + "消证兑换积分", disappearCount.toString());
        }

    }

    @Autowired
    private IFwShangjiaDealService shangjiaDealService;

    @Override
    public void returnShangJiaById() {
        //退回集市交易中的商甲可单独调用,可定时调用
        List<FwLogs> list = logsService.list(Wrappers.<FwLogs>lambdaQuery().eq(FwLogs::getIsType, "撤回").last(" AND  to_days(create_time) = to_days(now())"));
        if (list.size() <= 0) {
            shangjiaDealService.list(Wrappers.<FwShangjiaDeal>lambdaQuery().eq(FwShangjiaDeal::getType, 0)).forEach(item -> {
                //开始执行退回
                FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, item.getUserId()));
                moneysService.updateById(moneys.setShangJia(moneys.getShangJia().add(item.getCount())));

                logsService.saveLogs(item.getUserId(), item.getUserId(), LogsTypeEnum.MONEY_SELL_RETURN.getTypeName(), LogsModelEnum.SHANG_JIA_MODEL.getModelName(), "系统自动撤回" + item.getCount() + "商甲", item.getCount().toString());

                item.setCount(new BigDecimal(0));
                item.setType(1);
                shangjiaDealService.getBaseMapper().deleteById(item);
            });

        }

    }
}
